package com.kfyang.manualgear.daoplugin.generator;

import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.kfyang.manualgear.daoplugin.generator.ui.YmlGenerateUI;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class YmlGenerateDialogWrapper extends DialogWrapper {
    private final YmlGenerateUI generateUI;
    private final Document document;
    private final Project project;
    private final PsiFile psiFile;

    protected YmlGenerateDialogWrapper(@Nullable Project project, String methodName, Document document, PsiFile psiFile) {
        super(project);
        setTitle("Generate Options");
        setOKButtonText("Generate");
        setCancelButtonText("Cancel");

        this.document = document;
        this.project = project;
        this.psiFile = psiFile;

        generateUI = new YmlGenerateUI(project);
        generateUI.getMethodNameText().setText(methodName);

        super.init();
    }

    @Override
    protected void doOKAction() {
        String ymlText = generateUI.getYmlText();
        WriteCommandAction.runWriteCommandAction(project, () -> {
            document.insertString(document.getTextLength(), "\n---\n\n" + ymlText);
            FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
            NavigationUtil.activateFileWithPsiElement(psiFile, true);
            Editor editor = fileEditorManager.getSelectedTextEditor();
            assert editor != null;
            editor.getCaretModel().moveToOffset(document.getTextLength());
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        });
        super.doOKAction();
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return generateUI.getRootPanel();
    }
}
